package com.study.netty.demo1;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

/**
 * 客户端
 */
public class ClientDemo {

    /**
     * 连接服务端
     *
     * @param host
     * @param port
     * @throws Exception
     */
    public void connect(String host, int port) throws Exception {

        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            //EventLoop的组
            bootstrap.group(worker);
            //用于构造socketchannel工厂
            bootstrap.channel(NioSocketChannel.class);
            //设置长连接
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            //自定义客户端Handle（客户端在这里搞事情）
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) {
                    ch.pipeline().addLast("decoder", new StringDecoder(Charset.forName("GBK")));
                    ch.pipeline().addLast("encoder", new StringEncoder(Charset.forName("GBK")));
                    ch.pipeline().addLast(new SimpleClientHandler());
                }
            });
            //开启客户端监听
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();

            //等待数据直到客户端关闭
            channelFuture.channel().closeFuture().sync();
        } finally {
            worker.shutdownGracefully();
        }
    }
}
